const fs = require('fs');
const excel = require('node-xlsx');
const {
    httpClient
} = require('../app/lib');

let exportApis = (datas, fileName) => {
    let map = new Map();
    let apiInfoSheet = {
        name: '接口信息',
        data: [
            ['序号', '接口名', '版本', '概述', '描述', '公共参数', '接口类别', 'GET/POST', '所属项目', '所属模块']
        ]
    };

    let index = 1;
    let sheets = [apiInfoSheet];

    for (let key in datas.paths) {
        let item = datas.paths[key];
        let detail = item['get'] || item['post'] || item['put'] || item['delete'];

        if (detail) {
            apiInfoSheet.data.push(
                [
                    index++,
                    key,
                    '1.0',
                    detail.summary,
                    detail.summary,
                    '1',
                    '对日项目demo',
                    getHttpMethod(detail.operationId),
                    '',
                    ''
                ]
            );

            sheets.push(createApiDetail(datas, detail, key, index - 1));
        }
    }

    let excelBuffers = excel.build(sheets);

    fs.writeFile(`./out/${fileName}.xlsx`, excelBuffers, err => {
        if (err) {
            console.log('出现错误，错误详情：', err);
        } else {
            console.log('生成成功！');
        }
    });
};

let createApiDetail = (datas, detail, apiName, index) => {
    let sheet = {
        name: index + '',
        data: [
            ['接口名称', '类型', '字段编码', '字段类型', '字段长度', '是否必须', '示例值', '描述']
        ]
    };

    if (detail.parameters) {
        detail.parameters.forEach(p => {
            sheet.data.push([
                apiName,
                'req',
                p.name,
                p.type,
                p.length,
                p.required ? '是' : '否',
                '',
                p.description
            ]);
        });
    }

    if (detail.responses && detail.responses['200']) {
        if (detail.responses['200'].schema) {

            let ref = detail.responses['200'].schema['$ref'];
            let modeKey = ref.substring(ref.lastIndexOf('/') + 1);
            let model = datas.definitions[modeKey];

            if (model) {
                for (let pKey of Object.getOwnPropertyNames(model.properties)) {
                    let p = model.properties[pKey];

                    sheet.data.push([
                        apiName,
                        'res',
                        pKey,
                        p.type,
                        p.length,
                        p.required ? '是' : '否',
                        '',
                        p.description
                    ]);
                }
            }
        }
    }

    return sheet;
}

let getHttpMethod = (op) => {
    if (op.endsWith('GET')) {
        return 'GET';
    } else if (op.endsWith('POST')) {
        return 'POST';
    } else if (op.endsWith('PUT')) {
        return 'PUT';
    } else {
        return 'DELETE';
    }
}

let getApiDatas = () => {
    httpClient.get(`http://210.12.100.203:8001/v2/api-docs`).then(rs => {
        exportApis(JSON.parse(rs.body), '对日项目接口文档');
    }).catch(reason => console.log(reason));
};

getApiDatas();